#!/bin/bash

# 服务器连接问题诊断脚本
# 用于检查Node.js服务和网络连接状态

echo "=== 服务器连接问题诊断 ==="
echo "时间: $(date)"
echo

# 服务器信息
SERVER_IP="47.237.10.129"
SERVER_USER="root"
PORT="8080"

echo "正在连接服务器 $SERVER_IP..."
echo

# 执行远程诊断命令
ssh -o ConnectTimeout=10 $SERVER_USER@$SERVER_IP << 'EOF'
echo "=== 系统信息 ==="
echo "主机名: $(hostname)"
echo "系统时间: $(date)"
echo "系统负载: $(uptime)"
echo

echo "=== Node.js 进程检查 ==="
echo "Node.js 进程:"
ps aux | grep node | grep -v grep
echo

echo "=== 端口监听状态 ==="
echo "8080端口监听状态:"
netstat -tlnp | grep :8080 || echo "8080端口未被监听"
echo
echo "3000端口监听状态:"
netstat -tlnp | grep :3000 || echo "3000端口未被监听"
echo
echo "所有监听端口:"
netstat -tlnp | head -20
echo

echo "=== 防火墙状态 ==="
echo "iptables规则:"
iptables -L INPUT -n | grep 8080 || echo "未找到8080端口的iptables规则"
echo

echo "=== 服务日志检查 ==="
echo "后端服务日志 (最后20行):"
if [ -f "/var/log/backend.log" ]; then
    tail -20 /var/log/backend.log
else
    echo "日志文件 /var/log/backend.log 不存在"
fi
echo

echo "=== 本地连接测试 ==="
echo "本地curl测试 8080端口:"
curl -s -m 5 http://localhost:8080/health || echo "本地8080端口连接失败"
echo
echo "本地curl测试 3000端口:"
curl -s -m 5 http://localhost:3000/health || echo "本地3000端口连接失败"
echo

echo "=== 网络接口状态 ==="
echo "网络接口:"
ip addr show | grep -E "inet |UP|DOWN"
echo

echo "=== 后端目录状态 ==="
echo "后端目录内容:"
if [ -d "/opt/cumbull/backend" ]; then
    ls -la /opt/cumbull/backend/
    echo
    echo ".env.production 内容:"
    if [ -f "/opt/cumbull/backend/.env.production" ]; then
        grep -E "PORT|NODE_ENV" /opt/cumbull/backend/.env.production
    else
        echo ".env.production 文件不存在"
    fi
else
    echo "后端目录 /opt/cumbull/backend 不存在"
fi
echo

echo "=== 诊断完成 ==="
EOF

echo
echo "=== 外部连接测试 ==="
echo "从本地测试服务器连接:"
echo "测试 http://$SERVER_IP:$PORT/health"
curl -s -m 10 http://$SERVER_IP:$PORT/health || echo "外部连接失败"
echo
echo "测试 http://$SERVER_IP:$PORT/api"
curl -s -m 10 http://$SERVER_IP:$PORT/api || echo "外部API连接失败"
echo

echo "=== 诊断脚本执行完成 ==="
echo "如果发现问题，请根据诊断结果进行相应修复"